package top.guinguo.analyzer_03.util;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;

import java.io.IOException;
import java.util.Stack;

/**
 * Created by guin_guo on 2016/12/22.
 */
public class MySameTokenFilter extends TokenFilter {

    private CharTermAttribute cta = null;
    private PositionIncrementAttribute pia = null;

    private Stack<String> sws = null;
    private TokenFilter.State current = null;
    private SameWordContext sameWordContext;
    /**
     * Construct a token stream filtering the given input.
     *
     * @param input
     */
    protected MySameTokenFilter(TokenStream input, SameWordContext sameWordContext) {
        super(input);
        cta = this.addAttribute(CharTermAttribute.class);
        pia = this.addAttribute(PositionIncrementAttribute.class);
        sws = new Stack<String>();
        this.sameWordContext = sameWordContext;
    }

    public final boolean incrementToken() throws IOException {
        if (sws.size() > 0) {
            //将元素出栈，并且获取这个同义词
            String sword = sws.pop();
            //还原状态
            restoreState(current);
            cta.setEmpty();
            cta.append(sword);
            //设置位置增长为0，继续当前位置，默认是1
            pia.setPositionIncrement(0);
            return true;
        }
        if (!input.incrementToken()) return false;

        if (addSameWord(cta.toString())) {
            //如果有同义词将当前状态先保存
            current = captureState();
        }
        return true;
    }

    public boolean addSameWord(String key) {
        String[] sas = sameWordContext.getSameWord(key);
        if (sas != null) {
            for (String s : sas) {
                sws.push(s);
            }
            return true;
        }
        return false;
    }
    /*public final boolean incrementToken() throws IOException {
        if (!input.incrementToken()) {
            return false;
        }
        String[] sames = getSameWord(cta.toString());
        if (sames != null) {
            pia.setPositionIncrement(pia.getPositionIncrement() - 1);
            for (String s : sames) {
                System.out.println(s);
            }
        }
        *//*if (cta.toString().equals("中国")) {
            cta.setEmpty();
            cta.append("大陆");
        }*//*
//        System.out.print(cta+"==");
        return true;
    }*/

    /*private String[] getSameWord(String key) {
        Map<String, String[]> sames = new HashMap<String, String[]>();
        sames.put("中国", new String[]{"大陆", "天朝"});
        return sames.get(key);
    }*/
}
